package com.hanlyjiang.library.utils;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * Created by jianghanghang on 2017/1/19.
 */

public class SimpleHttpUtils {
    private static final int TIME_OUT_5000 = 5000;
    private static final boolean DEBUG = true;

    /**
     * 做Get 请求，并且获取返回json 字符串
     * @param url
     * @return 返回内容
     * @throws IOException
     */
    public static String doGet(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(TIME_OUT_5000);
        BufferedInputStream in = new BufferedInputStream(urlConnection.getInputStream());
        InputStreamReader reader = new InputStreamReader(in);
        try {
            if(DEBUG){
                String info = readStream(reader);
                log(url.toString(),"Response" ,info);
                return info;
            }else{
                return readStream(reader);
            }
        } finally {
            reader.close();
            in.close();
            urlConnection.disconnect();
        }
    }

    public static InputStream doGetStream(URL url) throws IOException {
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setConnectTimeout(TIME_OUT_5000);
        return urlConnection.getInputStream();
    }

    private static void log(String url, String action, String info){
        System.out.println(String.format("Request: %s ; %s;  %s ",
                url,action,info));
    }

    /**
     * 流转string
     * @param reader  InputStreamReader
     * @return  内容 string
     * @throws IOException
     */
    private static String readStream(InputStreamReader reader) throws IOException {
        char[] buffer = new char[4096];
        StringBuffer result = new StringBuffer();
        int index = 0;
        int size = 0;
        while( (size = reader.read(buffer, index, 4096)) != -1 ){
            result.append(buffer, index, size);
        }
        return result.toString();
    }
}
